import React, {useState, useRef, useEffect} from 'react';
import './App.css';
import {Button, Card, Row, Col, Form, Input, Select, Upload, Modal, Avatar, Spin} from 'antd';
import {UploadOutlined, UserOutlined, AlibabaOutlined} from '@ant-design/icons';
import ws from '../utils/ws';

const MediaStreamRecorder = require('msr');

const {Option} = Select;

function Example() {
    // 接受到的消息
    const [socket, setSocket] = useState(null);
    // 发送出去的消息
    const [ping, setPing] = useState([]);
    // 客服咨询弹窗
    const [advisoryVisible, setAdvisoryVisible] = useState(false);
    // 文件上传中
    const [loading, setLoading] = useState(false);
    // 视频上传实例
    const [videoVisible, setVideoVisible] = useState(false);
    // 视频播放实例
    const video = useRef(null);
    // 输入框实例
    const input = useRef(null);

    useEffect(() => {
        window.addEventListener('keydown', handleUserKeyPress);

        return () => {
            window.removeEventListener('keydown', handleUserKeyPress);
        };
    });

    // 监听enter按钮
    const handleUserKeyPress = (event) => {
        if (event.keyCode === 13) {
            sendOut();
        }
    };


    // 开始录制视频
    const openVideo = () => {
        navigator.mediaDevices.getUserMedia({
            video: {width: '100%', height: '100%'},
        }).then((stream) => {
            if (video.current) {
                video.current.srcObject = stream;
                convertStreamToBlob(stream)
            }
        });
    }

    // 将媒体流数据转化成blob数据
    const convertStreamToBlob = (stream) => {
        const mediaRecorder = new MediaStreamRecorder(stream);
        mediaRecorder.mimeType = 'video/mp4';
        mediaRecorder.ondataavailable = function (blob) {
            uploadToServer(blob);
        };
        mediaRecorder.start(3000);
    }

    // 上传数据至服务器
    const uploadToServer = (blob) => {
        const file = new File([blob], 'msr-' + (new Date()).toISOString().replace(/:|\./g, '-') + '.mp4', {
            type: 'video/mp4'
        });

        const formData = new FormData();
        formData.append(`video-filename`, file.name);
        formData.append('video-blob', file);

        fetch('http://example.com/movies.json', {
            body: formData,
            method: 'POST',
            mode: 'cors',
        })
            .then(function (response) {
                return response.json();
            })
            .then(function (myJson) {
                console.log(myJson);
            }).catch((e) => {
                console.log(e);
        })

        stopStreamedVideo();
    }

    // 关闭媒体流录制
    const stopStreamedVideo = () => {
        const stream = video.current.srcObject;
        const tracks = stream.getTracks();

        tracks.forEach(function (track) {
            track.stop();
        });

        video.current.srcObject = null;
        setVideoVisible(false);
    }


    const fileList = [
        {
            uid: '-1',
            name: 'xxx.png',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
            thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        },
        {
            uid: '-2',
            name: 'yyy.png',
            status: 'error',
        },
    ];

    // 连接 socket
    const beginAdvisory = () => {
        const _ws = ws('1609670148172', '123');

        _ws.onmessage = (e) => {
            const data = e.data;
            const dataObj = eval("(" + data + ")");//转换为json对象
            if (dataObj.command == 11) {//接收到聊天响应处理;
            } else if (dataObj.command == 18) {//获取用户信息响应处理;
            } else if (10000 == dataObj.code && dataObj.command == 12) {//聊天发送状态;
            } else if (dataObj.command == 9) {//加入群组的消息通知处理;
            } else if (dataObj.command == 10) {
            } else if (dataObj.command == 20 && dataObj.code == 10015) {
                //获取消息失败，未开启持久化处理
                //...
            } else if (dataObj.command == 20 && dataObj.code == 10016) {//处理离线消息;
                const msgFlag = "离线消息";
            } else if (dataObj.command == 20 && dataObj.code == 10018) {//处理历史消息;
                const msgFlag = "历史消息";
                const msgObj = dataObj.data;
                if (msgObj) {
                } else {//没有历史消息;
                }
            } else if (dataObj.command == 6) {//登陆命令返回状态处理
            } else {
            }
        };

        setSocket(_ws);
        setAdvisoryVisible(true);
    }

    // 结束socket
    const endAdvisory = () => {
        socket.close();
        setSocket(null);
        setAdvisoryVisible(false);
    }

    // 发送消息
    const sendOut = () => {
        if (input.current.value) {
            const temp = [...ping];
            temp.push(input.current.value);
            setPing(temp);
            input.current.value = '';
        }
    }

    return (
        <div>
            <Spin spinning={loading} tip="文件上传中">
                <div className={'header'}>
                    表单
                </div>
                <Card>
                    <Card
                        style={{marginTop: 16}}
                        type="inner"
                        title="表单填写"
                    >
                        <Row gutter={16}>
                            <Col lg={6} md={12} sm={24}>
                                <Form.Item
                                    label={'仓库名称'}
                                    name="name"
                                    rules={[{required: true, message: '请输入仓库名称'}]}
                                >
                                    <Input placeholder="请输入仓库名称"/>
                                </Form.Item>
                            </Col>
                            <Col xl={{span: 6, offset: 2}} lg={{span: 8}} md={{span: 12}} sm={24}>
                                <Form.Item
                                    label={'仓库名称'}
                                    name="name"
                                    rules={[{required: true, message: '请输入仓库名称'}]}
                                >
                                    <Input placeholder="请输入仓库名称"/>
                                </Form.Item>
                            </Col>
                            <Col xl={{span: 8, offset: 2}} lg={{span: 10}} md={{span: 24}} sm={24}>
                                <Form.Item
                                    label={'仓库名称'}
                                    name="owner"
                                    rules={[{required: true, message: '请选择管理员'}]}
                                >
                                    <Select placeholder="请选择管理员">
                                        <Option value="xiao">付晓晓</Option>
                                        <Option value="mao">周毛毛</Option>
                                    </Select>
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col lg={6} md={12} sm={24}>
                                <Form.Item
                                    label={'仓库名称'}
                                    name="approver"
                                    rules={[{required: true, message: '请选择审批员'}]}
                                >
                                    <Select placeholder="请选择审批员">
                                        <Option value="xiao">付晓晓</Option>
                                        <Option value="mao">周毛毛</Option>
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col xl={{span: 8, offset: 2}} lg={{span: 10}} md={{span: 24}} sm={24}>
                                <Form.Item
                                    label={'仓库名称'}
                                    name="approver"
                                    rules={[{required: true, message: '请选择审批员'}]}
                                >
                                    <Select placeholder="请选择审批员">
                                        <Option value="xiao">付晓晓</Option>
                                        <Option value="mao">周毛毛</Option>
                                    </Select>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Card>
                    <Card
                        style={{marginTop: 16}}
                        type="inner"
                        title="文件资源上传"
                    >
                        <Upload
                            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            listType="picture"
                            defaultFileList={[...fileList]}
                        >
                            <Button icon={<UploadOutlined/>}>Upload</Button>
                        </Upload>
                        <br/>
                        <br/>
                    </Card>
                </Card>
                <div className={'fixed-widgets'} onClick={() => setVideoVisible(true)}>
                <span
                    className={'fixed-widgets-avatar'}>
                    <Avatar size={36} icon={<AlibabaOutlined/>} style={{color: '#000', backgroundColor: '#fff'}}/>
                </span>
                </div>
                <div className={'footer'}>
                    <Button type="primary" size={'large '}>
                        提交
                    </Button>
                </div>

                <Modal
                    title="视频上传"
                    centered
                    visible={videoVisible}
                    width={1000}
                    okText={'录制'}
                    cancelText={'取消'}
                    onOk={openVideo}
                    onCancel={stopStreamedVideo}
                    bodyStyle={{height: 600}}
                >
                    <div className={'modal'}>
                        <video autoPlay ref={video} style={{width: '100%', height: '100%'}}/>
                    </div>
                </Modal>

                <Modal
                    title="咨询客服"
                    centered
                    visible={advisoryVisible}
                    onCancel={() => setAdvisoryVisible(false)}
                    footer={null}
                    width={1000}
                    bodyStyle={{height: 600}}
                >
                    <div className={'modal'}>
                        <div className={'modal-content'}>
                            <div className={'customer-service'}>
                                <p className="message--pin">智能客服啊戳戳</p>
                                <Avatar size={32} icon={<UserOutlined/>}/>
                                <div data-v-77a3087f="" className="text-message--container">
                                    <p>您是想问以下问题吗？可以直接点击哦。如果不是，请直接在输入框提问哦~</p></div>
                            </div>
                            {
                                ping.map(item =>
                                    <div className={'customer'} key={item}>
                                        <p className="message--pin">a18091183170</p>
                                        <div>
                                            <div className="text-message--container">
                                                <p>{item}</p></div>
                                            <Avatar size={32} icon={<UserOutlined/>}/>
                                        </div>
                                    </div>)
                            }
                        </div>
                        <div className={'modal-foot'}>
                        <textarea name="textarea" rows="10" cols="50" ref={input}>
                        </textarea>
                            <span>
                            <Button style={{float: 'right', margin: 5}} onClick={sendOut}>发送</Button>
                        </span>
                        </div>
                    </div>
                </Modal>
            </Spin>
        </div>
    );
}

export default Example;